#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "kylin-activation.h"
#include "text-i18n.h"

/*
 * kylin_activation_print_result_message, print message according to result number
 */
extern void kylin_activation_print_result_message(int result);

/*
 * _code_remove_hyphen, remove hyphen in code
 */
static void _code_remove_hyphen(char* code)
{
	char* buf = NULL;
	int i = 0;
	int j = 0;

	buf = strdup(code);
	if(!buf)
		return ;

	memset(code, 0, strlen(code));
	while(buf[j] != '\0')
	{
		while(buf[j] == '-')
			++j;

		code[i] = buf[j];
		++i;
		++j;
	}

	free(buf);
}

int main(int argc, char** argv)
{
	int result;
	char* register_code = NULL;
	char* serial = NULL;
	char* p;

	setlocale(LC_MESSAGES, "");
	bindtextdomain (PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
	bind_textdomain_codeset(PACKAGE, "utf8");

	if(argc == 1)
	{
		register_code = kylin_activation_get_register_number(&result);
	} else if (argc == 2) {
		register_code = kylin_activation_get_register_number_with_serial(argv[1], &result);
	}
	if(!register_code || result != NO_ERROR)
	{
		kylin_activation_print_result_message(result);
		exit(result);
	}

	serial = kylin_activation_get_serial_number(&result);
	if(result != NO_ERROR)
	{
		kylin_activation_print_result_message(result);
		exit(result);
	}

	if(register_code)
	{
		if((p = getenv("CODE_NO_HYPHEN")) && (strncmp(p, "y", 1) == 0))
		{
			_code_remove_hyphen(register_code);
			printf("%s\n", register_code);
		}
		else
			printf("%s\n", register_code);
	}

	if(serial)
	{
		if((p = getenv("SHOW_SERIAL_NO")) && (strncmp(p, "y", 1) == 0))
			printf("%s\n", serial);
	}

	if(register_code)
		free(register_code);
	if(serial)
		free(serial);

	exit(result);
}
